<?php
/**
 * The Imagess model class for abstracting operations to the Images Entity
 *
 */

class Images extends Zend_Db_Table
{
    protected $_name = 'images'; // The name of the database entity
    protected $_primary = 'pid'; // The primary key associated with this table

    //Declare the relational links to other Database entities
    protected $_referenceMap    = array(
        'Item' => array(
            'columns'           => 'id',
            'refTableClass'     => 'Items',
            'refColumns'        => 'id'
        ),
        'Gallery' => array(
            'columns'           => 'pid',
            'refTableClass'     => 'Items',
            'refColumns'        => 'gallery'
        )
    );

    public function getById($id)
    {
        return $this->fetchAll($this->select()->where('id = ?', $id));
    }

    public function removeImagesById($id)
    {
        $rows = $this->fetchAll($this->select()->where('id = ?', $id));
        foreach($rows as $row)
        {
            $path = getcwd() . '/host/' . $row->filename;
            if(file_exists($path) && fclose($path))
            {
                unlink($path);
            }
            $row->delete();
        }
    }

    public function removeImageByPid($pid)
    {
        $row = $this->fetchRow($this->select()->where('pid = ?', $pid));
        $path = getcwd() . '/host/' . $row->filename;
        if(file_exists($path))
        {
            unlink($file);
        }
        $row->delete();
    }
}
